'''
@Author: your name
@Date: 2020-02-05 11:23:33
LastEditTime: 2021-04-02 09:34:32
LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /tinyms/tinyms-api/apps/utils/auth.py
'''
from app import app
from flask import Flask, jsonify,request,g,current_app
import json
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, BadSignature
from functools import wraps


# 生成token，有效时间100min
def create_auth_token(api_user):
    s = Serializer(app.config['SECRET_KEY'], expires_in = 6000)
    token = s.dumps({"id":api_user}).decode("ascii")
    return token

#token验证
@staticmethod
def verify_auth_token(token):
    s = Serializer(app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except SignatureExpired:
        return None # valid token, but expired
    except BadSignature:
        return None # invalid token
    user = User.query.get(data['id'])
    return user


# 登录验证（会调用token验证函数）
def login_required(view_func):
    @wraps(view_func)
    def verify_token(*args,**kwargs):
        try:
            #在请求头上拿到token
            token = request.headers["accessToken"]
            # token = request.header.get_all("token")
            app.logger.info("accessToken"+token)
        except Exception:
            #没接收的到token,给前端抛出错误
            #这里的code推荐写一个文件统一管理。这里为了看着直观就先写死了。
            app.logger.debug("未获取到token信息")
            return jsonify(code = 4103,msg = '缺少参数token,请登录!')
        
        s = Serializer(current_app.config["SECRET_KEY"])
        try:
            s.loads(token)
        except Exception:
            return jsonify(code = 4101,msg = "登录已过期")

        return view_func(*args,**kwargs)

    return verify_token

#输出请求头部信息
def print_header():
    headers = request.headers
    response = ""
    for k,v in headers.items():
        response += "%s : %s<br/>" % (k,v)
        current_app.logger.debug(response)